package com.u2ds.console.web.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpUtil {

	public static String post(String url, Map<String, String> params) {
		String result = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if(params!=null){
				Set<String> keySet = params.keySet();
				for (String key : keySet) {
					System.out.println(key  +"=" + params.get(key));
					nvps.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}

			CloseableHttpClient client = HttpClients.createDefault();
			HttpResponse response = null;
			try {
				response = client.execute(httpPost);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			if (response.getStatusLine().getStatusCode() == 200) {
				try {
					result = EntityUtils.toString(response.getEntity());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
